<?php

namespace App\Models\Applet\Sponsor;

class SponsorCategoryModel extends BaseSponsorModel
{
    protected $table = 'sponsor_category';

    /**
     * 总条数
     * @return void
     */
    public function total(array $params)
    {
        $query = $this->where('deleted', self::DELETED_NO);
        if (!empty($params['title'])) {
            $query = $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        return $query->count();
    }

    /**
     * 列表
     * @param array $params
     * @param array $fields
     * @return array
     */
    public function list(array $params, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $query = $this->select($fields);
        if (!empty($params['title'])) {
            $query = $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        return $query
            ->where('deleted', self::DELETED_NO)
            ->orderBy('id', 'asc')
            ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
            ->limit(PAGE_SIZE)
            ->get()
            ->toArray();
    }

    /**
     * 根据标题获取数据
     * @param string $title
     * @param string[] $fields
     * @return array
     */
    public function getItemByTitle(string $title, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('title', $title)
                       ->where('deleted', self::DELETED_NO)
                       ->first();
        return $result ? $result->toArray() : [];
    }

}
